//
//  SIXAdvertisementView.m
//  图片轮播
//
//  Created by 张天兵 on 16/5/20.
//  Copyright © 2016年 张天兵. All rights reserved.
//

#import "SIXAdvertisementView.h"

#define scrollViewW self.scrollView.frame.size.width
#define scrollViewH self.scrollView.frame.size.height
const int count = 4;


@interface SIXAdvertisementView()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
/** 定时器 */
@property(nonatomic, weak) NSTimer *timer;

@end


@implementation SIXAdvertisementView

#pragma mark - 生命周期
- (void)awakeFromNib {
    // 添加图片
    [self setImages];
    
    // 设置contentSize
    self.scrollView.contentSize = CGSizeMake(count * scrollViewW, 0);
    
    // 开启分页功能
    self.scrollView.pagingEnabled = YES;
    
    // 设置总页数
    self.pageControl.numberOfPages = count;
    
    // 设置pageControl单页的时候是否隐藏
    self.pageControl.hidesForSinglePage = YES;
    
    // 开启定时器
    [self startTimer];
    
    // 设置代理
    self.scrollView.delegate = self;

}

- (void)setImages {
    
    for (int  i = 0; i < count; i ++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        // 获取图片名
        imageView.image = [UIImage imageNamed:@"square_ad"];
        imageView.frame = CGRectMake(i * scrollViewW, 0, scrollViewW, scrollViewH);
        [self.scrollView addSubview:imageView];
    }

}

#pragma mark - 定时器相关方法
// 开启定时器
- (void)startTimer {
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextPage:) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

// 停止定时器
- (void)stopTimer {
    [self.timer invalidate];
}

// 滚动至下一页
- (void)nextPage:(NSTimer *)timer {
    
    NSInteger page = self.pageControl.currentPage + 1;
    
    if (page == count) {
        page = 0;
    }

    [self.scrollView setContentOffset:CGPointMake(page * scrollViewW, 0) animated:YES];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 计算页码
    int page =  (int)(scrollView.contentOffset.x / scrollView.frame.size.width + 0.5);
    
    // 设置页码
    self.pageControl.currentPage = page;
}

// 用户即将开始拖拽scrollView,停止定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    [self stopTimer];
}

// 用户已经停止拖拽scrollView,开启定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}


@end
